import { createDiscreteApi, type ConfigProviderProps } from 'naive-ui'
import type { MessageApi, DialogApi, NotificationApi, LoadingBarApi } from 'naive-ui'

declare global {
  interface Window {
    $message: MessageApi
    $dialog: DialogApi
    $notification: NotificationApi
    $loadingBar: LoadingBarApi
  }
}

interface DiscreteApiOptions {
  theme?: ConfigProviderProps['theme']
  themeOverrides?: ConfigProviderProps['themeOverrides']
}

export class DiscreteApi {
  private static instance: DiscreteApi | null = null
  private static isInitialized = false

  private constructor(options?: DiscreteApiOptions) {
    const { message, dialog, notification, loadingBar } = createDiscreteApi(
      ['message', 'dialog', 'notification', 'loadingBar'],
      {
        configProviderProps: {
          theme: options?.theme,
          themeOverrides: options?.themeOverrides
        }
      }
    )

    window.$message = message
    window.$dialog = dialog
    window.$notification = notification
    window.$loadingBar = loadingBar
    DiscreteApi.isInitialized = true
  }

  public static getInstance(options?: DiscreteApiOptions): DiscreteApi {
    if (!DiscreteApi.instance) {
      DiscreteApi.instance = new DiscreteApi(options)
    }
    return DiscreteApi.instance
  }

  public static destroyInstance(): void {
    if (DiscreteApi.isInitialized) {
      // 使用类型断言处理销毁时的类型
      window.$message = null as unknown as MessageApi
      window.$dialog = null as unknown as DialogApi
      window.$notification = null as unknown as NotificationApi
      window.$loadingBar = null as unknown as LoadingBarApi
      DiscreteApi.instance = null
      DiscreteApi.isInitialized = false
    }
  }

  public static reconfigure(options: DiscreteApiOptions): void {
    this.destroyInstance()
    this.getInstance(options)
  }
}
